from django.db import models
from django.conf import settings
from decimal import Decimal
from portfolios.models import Portfolio, PortfolioHolding
from products.models import Product

# 监控类型
MONITORING_TYPES = [
    ('allocation_deviation', '配置偏离监控'),
    ('concentration_risk', '集中度风险监控'),
    ('stop_loss_warning', '止损预警监控'),
    ('performance_tracking', '业绩跟踪监控'),
    ('bond_yield_monitoring', '国债收益率监控'),
]

# 预警级别
ALERT_LEVELS = [
    ('info', '信息'),
    ('warning', '警告'),
    ('critical', '严重'),
    ('urgent', '紧急'),
]

# 预警状态
ALERT_STATUS = [
    ('active', '激活'),
    ('acknowledged', '已确认'),
    ('resolved', '已解决'),
    ('dismissed', '已忽略'),
]

# 报告类型
REPORT_TYPES = [
    ('quarterly', '季度报告'),
    ('monthly', '月度报告'),
    ('annual', '年度报告'),
    ('custom', '自定义报告'),
]

# 报告状态
REPORT_STATUS = [
    ('generating', '生成中'),
    ('completed', '已完成'),
    ('failed', '生成失败'),
]

class MonitoringRule(models.Model):
    """监控规则模型"""
    name = models.CharField(max_length=100, verbose_name='规则名称')
    monitoring_type = models.CharField(max_length=30, choices=MONITORING_TYPES, verbose_name='监控类型')
    description = models.TextField(blank=True, verbose_name='规则描述')
    
    # 监控参数
    threshold_value = models.DecimalField(max_digits=10, decimal_places=4, verbose_name='阈值')
    comparison_operator = models.CharField(max_length=10, choices=[
        ('gt', '大于'),
        ('gte', '大于等于'),
        ('lt', '小于'),
        ('lte', '小于等于'),
        ('eq', '等于'),
        ('ne', '不等于'),
    ], default='gt', verbose_name='比较操作符')
    
    # 预警设置
    alert_level = models.CharField(max_length=20, choices=ALERT_LEVELS, default='warning', verbose_name='预警级别')
    is_active = models.BooleanField(default=True, verbose_name='是否激活')
    
    # 时间戳
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        verbose_name = '监控规则'
        verbose_name_plural = '监控规则'
        db_table = 'monitoring_rules'
    
    def __str__(self):
        return f"{self.name} - {self.get_monitoring_type_display()}"

class PortfolioMonitoring(models.Model):
    """投资组合监控记录"""
    portfolio = models.ForeignKey(Portfolio, on_delete=models.CASCADE, verbose_name='投资组合')
    monitoring_rule = models.ForeignKey(MonitoringRule, on_delete=models.CASCADE, verbose_name='监控规则')
    
    # 监控数据
    current_value = models.DecimalField(max_digits=15, decimal_places=4, verbose_name='当前值')
    threshold_value = models.DecimalField(max_digits=15, decimal_places=4, verbose_name='阈值')
    deviation = models.DecimalField(max_digits=10, decimal_places=4, verbose_name='偏离度')
    
    # 监控结果
    is_triggered = models.BooleanField(default=False, verbose_name='是否触发')
    trigger_reason = models.TextField(blank=True, verbose_name='触发原因')
    
    # 时间戳
    check_time = models.DateTimeField(auto_now_add=True, verbose_name='检查时间')
    
    class Meta:
        verbose_name = '投资组合监控记录'
        verbose_name_plural = '投资组合监控记录'
        db_table = 'portfolio_monitoring'
        ordering = ['-check_time']
    
    def __str__(self):
        return f"{self.portfolio.name} - {self.monitoring_rule.name} - {self.check_time}"

class Alert(models.Model):
    """预警模型"""
    portfolio = models.ForeignKey(Portfolio, on_delete=models.CASCADE, verbose_name='投资组合')
    monitoring_record = models.ForeignKey(PortfolioMonitoring, on_delete=models.CASCADE, null=True, blank=True, verbose_name='监控记录')
    
    # 预警信息
    alert_type = models.CharField(max_length=30, choices=MONITORING_TYPES, verbose_name='预警类型')
    alert_level = models.CharField(max_length=20, choices=ALERT_LEVELS, verbose_name='预警级别')
    title = models.CharField(max_length=200, verbose_name='预警标题')
    message = models.TextField(verbose_name='预警消息')
    
    # 相关数据
    alert_data = models.JSONField(null=True, blank=True, verbose_name='预警数据')
    
    # 状态管理
    status = models.CharField(max_length=20, choices=ALERT_STATUS, default='active', verbose_name='状态')
    acknowledged_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, verbose_name='确认人')
    acknowledged_at = models.DateTimeField(null=True, blank=True, verbose_name='确认时间')
    resolved_at = models.DateTimeField(null=True, blank=True, verbose_name='解决时间')
    
    # 时间戳
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        verbose_name = '预警'
        verbose_name_plural = '预警'
        db_table = 'alerts'
        ordering = ['-created_at']
    
    def __str__(self):
        return f"{self.title} - {self.get_alert_level_display()}"

class QuarterlyReport(models.Model):
    """季度报告模型"""
    portfolio = models.ForeignKey(Portfolio, on_delete=models.CASCADE, verbose_name='投资组合')
    
    # 报告基本信息
    report_type = models.CharField(max_length=20, choices=REPORT_TYPES, default='quarterly', verbose_name='报告类型')
    quarter = models.CharField(max_length=10, verbose_name='季度', help_text='格式：2024Q1')
    title = models.CharField(max_length=200, verbose_name='报告标题')
    
    # 报告数据
    start_date = models.DateField(verbose_name='开始日期')
    end_date = models.DateField(verbose_name='结束日期')
    
    # 业绩数据
    start_value = models.DecimalField(max_digits=15, decimal_places=2, verbose_name='期初价值')
    end_value = models.DecimalField(max_digits=15, decimal_places=2, verbose_name='期末价值')
    total_return = models.DecimalField(max_digits=10, decimal_places=4, verbose_name='总收益率')
    benchmark_return = models.DecimalField(max_digits=10, decimal_places=4, null=True, blank=True, verbose_name='基准收益率')
    
    # 风险指标
    volatility = models.DecimalField(max_digits=8, decimal_places=4, null=True, blank=True, verbose_name='波动率')
    max_drawdown = models.DecimalField(max_digits=8, decimal_places=4, null=True, blank=True, verbose_name='最大回撤')
    sharpe_ratio = models.DecimalField(max_digits=8, decimal_places=4, null=True, blank=True, verbose_name='夏普比率')
    
    # 配置分析
    allocation_analysis = models.JSONField(null=True, blank=True, verbose_name='配置分析')
    holdings_performance = models.JSONField(null=True, blank=True, verbose_name='持仓表现')
    
    # 调整建议
    recommendations = models.JSONField(null=True, blank=True, verbose_name='调整建议')
    
    # 报告状态
    status = models.CharField(max_length=20, choices=REPORT_STATUS, default='generating', verbose_name='状态')
    generated_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, verbose_name='生成人')
    
    # 时间戳
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        verbose_name = '季度报告'
        verbose_name_plural = '季度报告'
        db_table = 'quarterly_reports'
        unique_together = ['portfolio', 'quarter']
        ordering = ['-created_at']
    
    def __str__(self):
        return f"{self.portfolio.name} - {self.quarter} 季度报告"

class MarketIndicator(models.Model):
    """市场指标监控"""
    indicator_name = models.CharField(max_length=50, verbose_name='指标名称')
    indicator_code = models.CharField(max_length=20, unique=True, verbose_name='指标代码')
    
    # 指标数据
    current_value = models.DecimalField(max_digits=10, decimal_places=4, verbose_name='当前值')
    previous_value = models.DecimalField(max_digits=10, decimal_places=4, null=True, blank=True, verbose_name='前值')
    change_rate = models.DecimalField(max_digits=8, decimal_places=4, null=True, blank=True, verbose_name='变化率')
    
    # 阈值设置
    upper_threshold = models.DecimalField(max_digits=10, decimal_places=4, null=True, blank=True, verbose_name='上限阈值')
    lower_threshold = models.DecimalField(max_digits=10, decimal_places=4, null=True, blank=True, verbose_name='下限阈值')
    
    # 监控状态
    is_monitoring = models.BooleanField(default=True, verbose_name='是否监控')
    last_alert_time = models.DateTimeField(null=True, blank=True, verbose_name='最后预警时间')
    
    # 时间戳
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    
    class Meta:
        verbose_name = '市场指标'
        verbose_name_plural = '市场指标'
        db_table = 'market_indicators'
    
    def __str__(self):
        return f"{self.indicator_name} ({self.indicator_code}): {self.current_value}"

class RebalanceRecommendation(models.Model):
    """再平衡建议"""
    portfolio = models.ForeignKey(Portfolio, on_delete=models.CASCADE, verbose_name='投资组合')
    
    # 建议信息
    recommendation_type = models.CharField(max_length=30, choices=[
        ('allocation_drift', '配置漂移'),
        ('market_timing', '市场时机'),
        ('risk_adjustment', '风险调整'),
        ('performance_optimization', '业绩优化'),
    ], verbose_name='建议类型')
    
    priority = models.CharField(max_length=20, choices=[
        ('low', '低'),
        ('medium', '中'),
        ('high', '高'),
        ('urgent', '紧急'),
    ], default='medium', verbose_name='优先级')
    
    # 建议内容
    title = models.CharField(max_length=200, verbose_name='建议标题')
    description = models.TextField(verbose_name='建议描述')
    
    # 调整方案
    current_allocation = models.JSONField(verbose_name='当前配置')
    target_allocation = models.JSONField(verbose_name='目标配置')
    adjustment_actions = models.JSONField(verbose_name='调整操作')
    
    # 预期效果
    expected_impact = models.JSONField(null=True, blank=True, verbose_name='预期影响')
    
    # 状态管理
    status = models.CharField(max_length=20, choices=[
        ('pending', '待处理'),
        ('accepted', '已接受'),
        ('rejected', '已拒绝'),
        ('implemented', '已实施'),
    ], default='pending', verbose_name='状态')
    
    # 时间戳
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    implemented_at = models.DateTimeField(null=True, blank=True, verbose_name='实施时间')
    
    class Meta:
        verbose_name = '再平衡建议'
        verbose_name_plural = '再平衡建议'
        db_table = 'rebalance_recommendations'
        ordering = ['-created_at']
    
    def __str__(self):
        return f"{self.portfolio.name} - {self.title}"